import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:flutter_xj_video/custom_drawer/drawer_item.dart';
import 'package:flutter_xj_video/custom_drawer/drawer_resource_controller.dart';
import 'package:flutter_xj_video/entity/film_entity.dart';
import 'package:flutter_xj_video/entity/film_page.dart';
import 'package:flutter_xj_video/entity/type_entity.dart';
import 'package:get/get.dart' as getx;
import 'package:dio/dio.dart';
import 'logic.dart';
import 'state.dart';
import 'package:xml2json/xml2json.dart';
import 'dart:convert' as convert;
import 'package:pull_to_refresh/pull_to_refresh.dart';

GlobalKey<_FilmListPageState> filmListKey = GlobalKey();

class FilmListPage extends StatefulWidget {
  FilmListPage({Key key}) : super(key: key);

  @override
  _FilmListPageState createState() => _FilmListPageState();
}

class _FilmListPageState extends State<FilmListPage> {
  final filmListLogic logic = getx.Get.put(filmListLogic());
  final filmListState state = getx.Get.find<filmListLogic>().state;
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  TextEditingController _editingController = TextEditingController();
  List<TypeEntity> typeList = [];
  TypeEntity currentType = TypeEntity(0, "最新");
  //总条数
  String recordcount = '';
  //总页数
  int pagecount = 0;
  //当前页
  int currentPage = 0;
  //总页数固定常量 因为不是从前向后翻页 所以下拉刷新不是1起
  int constPage;
  List<FilmRssListVideo> videoData = [];
  bool multiple = false;
  var searchKey = '';
  var currentYuan = DrawerItem(
    index: DrawerIndex.Mahuazy,
    labelName: '麻花资源',
    api: 'https://www.mhapi123.com/inc/api.php',
    icon: Icon(Icons.home),
  );

  @override
  void initState() {
    // log(FileResources().list.toString());
    // _editingController.addListener(() {
    //   log(_editingController.text);
    // });
    loadDataForType();
    super.initState();
  }

  void changeYuan(DrawerItem drawerItem) {
    setState(() {
      currentYuan = drawerItem;
    });
    loadDataForType();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Padding(
      padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          appBar(),
          toolBar(),
          Expanded(
              child: MediaQuery.removePadding(
                  removeTop: true,
                  context: context,
                  child: SmartRefresher(
                    enablePullDown: true,
                    enablePullUp: true,
                    controller: _refreshController,
                    onRefresh: _onRefresh,
                    onLoading: _onLoading,
                    child: multiple
                        ? StaggeredGridView.countBuilder(
                            itemCount: videoData.length,
                            crossAxisCount: 2,
                            itemBuilder: (context, index) {
                              return cell(videoData[index], context);
                            },
                            staggeredTileBuilder: (index) =>
                                StaggeredTile.fit(1),
                          )
                        : ListView.builder(
                            itemBuilder: (BuildContext context, int index) {
                              return normalCell(videoData[index], context);
                            },
                            itemCount: videoData.length,
                          ),
                  )))
        ],
      ),
    ));
  }

  Widget toolBar() {
    return Container(
      height: 80,
      padding: const EdgeInsets.all(5),
      color: Colors.white,
      child: Column(
        children: [
          Container(
            height: 35,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Text("当前源: " + currentYuan.labelName),
                GestureDetector(
                  onTap: () async {
                    showModalBottomSheet(
                        context: context,
                        builder: (context) {
                          return Container(
                              height: 500,
                              child: ListView.builder(
                                itemBuilder: (context, index) {
                                  return ListTile(
                                      onTap: () {
                                        setState(() {
                                          currentType = typeList[index];
                                        });
                                        loadDataForType();
                                        getx.Get.back();
                                      },
                                      title: Text(typeList[index].tname));
                                },
                                itemCount: typeList.length,
                              ));
                        });
                  },
                  child: Container(
                    padding: const EdgeInsets.only(
                        left: 5, right: 5, top: 2, bottom: 2),
                    decoration: BoxDecoration(
                        border: Border.all(color: Colors.grey, width: 1),
                        borderRadius: BorderRadius.all(Radius.circular(5))),
                    child: Text('分类: ' + currentType.tname + ' ▼'),
                  ),
                ),
                Text("共: " + recordcount.toString() + '资源')
              ],
            ),
          ),
          Container(
              decoration: BoxDecoration(
                  color: Colors.black12,
                  borderRadius: BorderRadius.all(Radius.circular(5))),
              padding: const EdgeInsets.only(left: 15, right: 15),
              height: 35,
              child: Row(
                children: [
                  Icon(Icons.search, size: 20),
                  SizedBox(
                    width: 5,
                  ),
                  Expanded(
                    child: Container(
                      height: 25,
                      child: TextField(
                        onEditingComplete: () {
                          setState(() {
                            searchKey = _editingController.text;
                          });
                          loadDataForType();
                          FocusScope.of(context).requestFocus(FocusNode());
                        },
                        textInputAction: TextInputAction.search,
                        controller: _editingController,
                        decoration: InputDecoration(
                            contentPadding: EdgeInsets.symmetric(vertical: 8),
                            border: InputBorder.none,
                            hintText: "请输入关键字"),
                      ),
                    ),
                  )
                ],
              ))
        ],
      ),
    );
  }

  Widget cell(FilmRssListVideo video, BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return GestureDetector(
      onTap: () {
        getx.Get.toNamed("/detail", arguments: [video, currentYuan]);
      },
      child: Container(
        decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(5)),
            color: Colors.white),
        margin: const EdgeInsets.all(5),
        child: Container(
          padding: const EdgeInsets.all(5),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Image.network(
                video.pic,
                fit: BoxFit.fill,
              ),
              Padding(
                padding: const EdgeInsets.only(top: 3, bottom: 3),
                child: Text(
                  video.name,
                  style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
                ),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Container(
                    constraints: BoxConstraints(maxWidth: size.width / 5),
                    child: Text(
                      video.type,
                      style: TextStyle(
                        color: Colors.grey,
                        fontSize: 14,
                      ),
                    ),
                  ),
                  SizedBox(
                    width: 2,
                  ),
                  Container(
                    constraints: BoxConstraints(maxWidth: size.width / 5.5),
                    child: Text(
                      video.note,
                      style: TextStyle(color: Colors.grey, fontSize: 14),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  Text(video.year,
                      style: TextStyle(color: Colors.grey, fontSize: 14))
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget normalCell(FilmRssListVideo video, BuildContext context) {
    return GestureDetector(
      onTap: () {
        getx.Get.toNamed("/detail", arguments: [video, currentYuan]);
      },
      child: Container(
        margin: const EdgeInsets.all(5),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(5)),
            color: Colors.white),
        child: Container(
          padding: const EdgeInsets.only(top: 8, bottom: 8),
          child: ListTile(
            title: Padding(
              padding: const EdgeInsets.only(bottom: 5),
              child: Text(video.name),
            ),
            leading: video.pic != null ? Image.network(video.pic) : SizedBox(),
            subtitle: Padding(
              padding: const EdgeInsets.only(top: 5),
              child: Text(video.type != null
                  ? video.type
                  : '' + ' | ' + video.year != null
                      ? video.year
                      : '' + ' | ' + video.note != null
                          ? video.note
                          : ''),
            ),
          ),
        ),
      ),
    );
  }

  Widget appBar() {
    return SizedBox(
        height: AppBar().preferredSize.height,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Padding(
                padding: EdgeInsets.only(top: 4),
                child: Container(
                  width: AppBar().preferredSize.height - 8,
                  height: AppBar().preferredSize.height - 8,
                )),
            Expanded(
              child: Center(
                child: Padding(
                  padding: const EdgeInsets.only(top: 4),
                  child: Text(
                    "香瓜影视",
                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                  ),
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(top: 8, right: 8),
              child: Container(
                width: AppBar().preferredSize.height - 8,
                height: AppBar().preferredSize.height - 8,
                // color: Colors.white,
                child: Material(
                  color: Colors.transparent,
                  child: InkWell(
                    child: Icon(
                      multiple ? Icons.dashboard : Icons.view_agenda,
                    ),
                    onTap: () {
                      setState(() {
                        multiple = !multiple;
                      });
                    },
                  ),
                ),
              ),
            )
          ],
        ));
  }

  void loadData(int page, bool isRef) async {
    Response response;
    var dio = Dio();
    dio.options.contentType = Headers.jsonContentType;
    dio.options.responseType = ResponseType.plain;
    var url = '';
    if (searchKey.length > 0) {
      url = currentYuan.api + '?wd=${searchKey}';
    } else {
      url = currentYuan.api +
          '?ac=videolist&t=${currentType.id}&pg=${isRef ? constPage : page}';
    }
    log(url);
    response = await dio.post(url);
    final myTransformer = Xml2Json();
    myTransformer.parse(response.data.toString());
    // var jsonStr = response.data.toString();
    var filmJson = myTransformer.toParker();
    Map<String, dynamic> jsonMap = convert.jsonDecode(filmJson);
    if (jsonMap['rss']['list']['video'] == null) {
      return;
    }
    log(jsonMap.toString());
    var filmEntity = FilmEntity().fromJson(jsonMap);
    var pageStr = myTransformer.toGData().replaceAll("list", "ipage");
    Map<String, dynamic> page_map = convert.jsonDecode(pageStr);
    var filmPageJson = Film_page.fromJson(page_map);

    var currentData = filmEntity.rss.xList.video;

    if (searchKey.length > 0) {
      List<FilmRssListVideo> currentDatatemp = [];
      for (var item in currentData) {
        if (searchKey.length > 0) {
          response =
              await dio.post(currentYuan.api + '?ac=videolist&ids=${item.id}');
          myTransformer.parse(response.data.toString());
          var detailJson = myTransformer.toParker();
          Map<String, dynamic> detailMap = convert.jsonDecode(detailJson);
          var detail =
              FilmRssListVideo().fromJson(detailMap['rss']['list']['video']);
          currentDatatemp.add(detail);
        }
      }
      currentData = currentDatatemp;
    }

    setState(() {
      if (isRef) {
        videoData = currentData;
      } else {
        videoData = videoData + currentData;
      }
    });
    _refreshController.loadComplete();

    // if (searchKey.length > 0) {
    //   log(jsonMap.toString());
    // } else {

    // }

    // if (videoData.length < 10) {
    //   loadData(pagecount - 1);
    // }
    //https://a.mhkuaibo.com/20200111/43DajJCg/index.m3u8
    // for (var index in videoData) {
    //   log(index.toJson().toString());
    // }
  }

  void _onRefresh() async {
    setState(() {
      pagecount = constPage;
    });
    loadData(constPage, true);
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    if (searchKey.length > 0) {
      _refreshController.loadNoData();
      return;
    }
    pagecount -= 1;
    loadData(pagecount, false);
    _refreshController.loadComplete();
  }

  //获取视频分类 及页数
  loadDataForType() async {
    Response response;
    var dio = Dio();
    dio.options.contentType = Headers.jsonContentType;
    dio.options.responseType = ResponseType.plain;
    var url = currentYuan.api + '?t=${currentType.id}';
    response = await dio.post(url);
    final myTransformer = Xml2Json();
    myTransformer.parse(response.data.toString());
    var typeJson = myTransformer.toGData().toString();
    var typeJsonStr =
        typeJson.replaceAll("\$t", "tname").replaceAll("__cdata", "cdata");
    var items = convert.jsonDecode(typeJsonStr)['rss']['class']['ty'];
    typeList = [TypeEntity(0, "最新")];
    for (var item in items) {
      TypeEntity action = TypeEntity(int.parse(item['id']), item['tname']);
      //过滤掉主分类
      const classToHide = ['电影', '电影片', '电视剧', '连续剧', '综艺', '动漫'];
      if (!classToHide.contains(action.tname)) {
        typeList.add(action);
      }
    }
    setState(() {
      recordcount = convert
          .jsonDecode(typeJsonStr)['rss']['list']['recordcount']
          .toString();
      //todo: 发现最后一页查询数据如果是1条的话  解析后的数据格式不是list 所以这里最新取倒数第二页
      pagecount = int.parse(
              convert.jsonDecode(typeJsonStr)['rss']['list']['pagecount']) -
          1;
      constPage = pagecount;
    });
    loadData(pagecount, true);
  }
}
